package com.fishV.BI.manager;

import com.fishV.BI.common.ErrorCode;
import com.fishV.BI.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author yuwei
 * @date 17:29 2024/10/19
 */
@Service
public class RedisLimiterManager {
    @Resource
    private RedissonClient client;

    public void rateLimit(String key, int rate, int interval) {

        RRateLimiter rateLimiter = client.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL,rate,interval, RateIntervalUnit.SECONDS);
        if(!rateLimiter.tryAcquire(1)){
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }
    }
}
